﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Patterns.Text
{
	/// <summary>
	/// Defines a rule for text manipulation.
	/// </summary>
	public class TextRule
	{
		/// <summary>
		/// The pattern.
		/// </summary>
		protected readonly CompiledRegex _pattern;

		/// <summary>
		/// The replacement text generator
		/// </summary>
		protected readonly Func<Match, string> _replacement;

		/// <summary>
		/// Initializes a new instance of the <see cref="TextRule"/> class.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="replacement">The replacement.</param>
		public TextRule(CompiledRegex pattern, Func<Match, string> replacement)
		{
			_pattern = pattern;
			_replacement = replacement;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="TextRule"/> class.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="replacement">The replacement.</param>
		public TextRule(CompiledRegex pattern, string replacement) : this(pattern, match => replacement) { }

		/// <summary>
		/// Applies the rule to the specified text.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <returns></returns>
		public virtual string Apply(string text)
		{
			return _pattern.IsMatch(text) ? _pattern.Replace(text, match => _replacement(match)) : null;
		}
	}
}